package Options::UserSync::UI::NewUser;

use base(DE_EPAGES::Presentation::UI::Object);
use strict;

use DE_EPAGES::Core::API::Log qw (LogDebug GetLog);
use DE_EPAGES::Customer::API::Shop qw (GetCustomerForUser);

use Options::Attributes::API::InterfaceCustomerGet;
use Options::Attributes::API::InterfaceCustomerUpdate;
use Options::UserSync::API::AddressFieldsConverter;
use Options::UserSync::API::ShopperID;
use DateTime;
use Data::Dumper;

sub NewUserLookup {
    my ( $self, $Servlet ) = @_;
    my $shop        = $Servlet->object;
    my $hMemberInfo = {};

    my $error_indicator = 0;

    GetLog->debug(" NewUserLookup TRIGGERED ");
    if ( defined $shop ) {
        my $button = $Servlet->params('cnRequest');
        if ( defined $Servlet->params('RequestCNvalue')
            && $Servlet->params('RequestCNvalue') eq 'custnumberrequest' )
        {
            GetLog->debug('cnRequest button is clicked');
            
    my $testPostcode    = $Servlet->params('testPostcode');
    if ( $testPostcode eq "" ) {
        $Servlet->vars( 'FormErrorx_testPostcode', 1 );
        $error_indicator = 1;
    }
    my $OptionsCustId = $Servlet->params('OptionsCustId');
    if ( $OptionsCustId eq "" ) {
        $Servlet->vars( 'FormErrorx_OptionsCustId', 1 );
        $error_indicator = 1;
    }          
            
            
            if ($error_indicator) {
                $Servlet->form->addFormError(
                    {   Reason => 'OptionsCustIdError',
                        Name   => 'OptionsCustId',
                    }
                );
                $Servlet->form->executeFormError();
            }
            
            my $customernumber    = trim( $Servlet->params('OptionsCustId') );
            my %UserSearchRequest = (
                'CustomerNumber'  => $customernumber,
                'GetAllCustomers' => 'false',
            );
            my $WSLinkGet
                = Options::Attributes::API::InterfaceCustomerGet::new(
                "Options::Attributes::API::InterfaceCustomerGet",
                "CustomerSearch",
                "CustomerSearchRequest",
                \%UserSearchRequest,
                "Customer"
                );
            my $hMemberInfo = $WSLinkGet->hitMe();

            if ( ref($hMemberInfo) ne "HASH" ) { $hMemberInfo = undef; }

            #user number was invalid error
            GetLog->debug( "Shop is defined: " . Dumper($hMemberInfo) );

            my $optionsPostcode = trim( lc( $hMemberInfo->{'Postcode'} ) );
            my $testPostcode = trim( lc( $Servlet->params('testPostcode') ) );

            GetLog->debug(" $optionsPostcode = $testPostcode ");

            if (   exists $hMemberInfo->{'CustomerNumber'}
                && $hMemberInfo->{'CustomerNumber'} eq $customernumber
                && $optionsPostcode eq $testPostcode )
            {

                my $AlternativeReference
                    = $hMemberInfo->{'AlternativeReference'};
                my $OptionsShopperID = $hMemberInfo->{'ShopperID'};
                if ( $OptionsShopperID eq '' || !defined($OptionsShopperID) )
                {
                    $OptionsShopperID
                        = &Options::UserSync::API::ShopperID::getNewShopperID(
                        $shop);
                }

                my $uname = $hMemberInfo->{'Email'};
                if ( $AlternativeReference ne '' ) {
                    $uname = $AlternativeReference;
                }

                # where to take it from ? ShopperID
                #        $Servlet->vars('CDSValid',1);
                $Servlet->form->{'Values'}->{'OptionsCustId'}
                    = [ $hMemberInfo->{'CustomerNumber'} ];
                $Servlet->form->{'Values'}->{'OptionsShopperID'}
                    = [$OptionsShopperID];
                $Servlet->form->{'Values'}->{'testPostcode'}
                    = [ $hMemberInfo->{'Postcode'} ];
                $Servlet->form->{'Values'}->{'Title'}
                    = [ $hMemberInfo->{'TitleCode'} ];

                $Servlet->form->{'Values'}->{'Company'}
                    = [ $hMemberInfo->{'AddressRef1'} ];
                $Servlet->form->{'Values'}->{'Department'}
                    = [ $hMemberInfo->{'AddressRef2'} ];

                $Servlet->form->{'Values'}->{'FirstName'}
                    = [ $hMemberInfo->{'FirstName'} ];
                $Servlet->form->{'Values'}->{'LastName'}
                    = [ $hMemberInfo->{'Surname'} ];
                $Servlet->form->{'Values'}->{'AddressExtension'}
                    = [ $hMemberInfo->{'Address1'} ];
                $Servlet->form->{'Values'}->{'Street'}
                    = [ $hMemberInfo->{'Address2'} ];
                $Servlet->form->{'Values'}->{'Street2'}
                    = [ $hMemberInfo->{'Address3'} ];
                $Servlet->form->{'Values'}->{'City'}
                    = [ $hMemberInfo->{'Town'} ];
                $Servlet->form->{'Values'}->{'Zipcode'}
                    = [ $hMemberInfo->{'Postcode'} ];
                $Servlet->form->{'Values'}->{'Phone'}
                    = [ $hMemberInfo->{'DayPhone'} ];
                $Servlet->form->{'Values'}->{'EMail'}
                    = [ $hMemberInfo->{'Email'} ];
                $Servlet->form->{'Values'}->{'UserName'} = [$uname];
                $Servlet->form->{'Values'}->{'CountryID'}
                    = [ $hMemberInfo->{'Country'} ];

                $Servlet->vars( 'OptionsCustId',
                    $hMemberInfo->{'CustomerNumber'} );
                $Servlet->vars( 'OptionsShopperID', $OptionsShopperID );
                $Servlet->vars( 'testPostcode', $hMemberInfo->{'Postcode'} );
                $Servlet->vars( 'Title',        $hMemberInfo->{'TitleCode'} );

                $Servlet->vars( 'Company',        $hMemberInfo->{'AddressRef1'} );
                $Servlet->vars( 'Department',        $hMemberInfo->{'AddressRef2'} );

                $Servlet->vars( 'FirstName',    $hMemberInfo->{'FirstName'} );
                $Servlet->vars( 'LastName',     $hMemberInfo->{'Surname'} );
                $Servlet->vars( 'AddressExtension',
                    $hMemberInfo->{'Address1'} );
                $Servlet->vars( 'Street',     $hMemberInfo->{'Address2'} );
                $Servlet->vars( 'Street2',    $hMemberInfo->{'Address3'} );
                $Servlet->vars( 'City',       $hMemberInfo->{'Town'} );
                $Servlet->vars( 'Zipcode',    $hMemberInfo->{'Postcode'} );
                $Servlet->vars( 'Phone',      $hMemberInfo->{'DayPhone'} );
                $Servlet->vars( 'EMail',      $hMemberInfo->{'Email'} );
                $Servlet->vars( 'Username',   $uname );
                $Servlet->vars( 'CountryID',  $hMemberInfo->{'Country'} );
                $Servlet->vars( 'ViewAction', 'ViewRegistration' );
                $Servlet->vars( 'ObjectID',   $shop->get('ObjectID') );
                $Servlet->form->addFormError(
                    {   Reason => 'CDSErrorSuccess',
                        Name   => 'cifnumberSuccess',
                    }
                );

                $Servlet->form->executeFormError();

            }
            else {

                #User number doesn't exist in the form
                #there is an error.. possibly user is not in CDS
                $Servlet->vars( 'CDSReason', $hMemberInfo->{'errorcode'} );
                $Servlet->form->addFormError(
                    {   Reason => 'CDSError',
                        Name   => 'OptionsCustId',
                    }
                );

#     $Servlet->form->{'Values'}->{'cifnumber'} = [$Servlet->params('cifnumber')];
#    $Servlet->form->{'Values'}->{'dob'} = [$Servlet->params('dob')];
#   $Servlet->form->{'Values'}->{'cds_surname'} = [$Servlet->params('cds_surname')];

                $Servlet->form->executeFormError();
            }

        }
        else {

            my $CustomerShopperID
                = &Options::UserSync::API::ShopperID::getNewShopperID($shop);
            $Servlet->form->{'Values'}->{'OptionsShopperID'}
                = [$CustomerShopperID];

            #              $Servlet->form->addFormError( {
            #                Reason => 'CDSError',
            #                 Name => 'cifnumber',
            #      });

#     $Servlet->form->{'Values'}->{'cifnumber'} = [$Servlet->params('cifnumber')];
#    $Servlet->form->{'Values'}->{'dob'} = [$Servlet->params('dob')];
#   $Servlet->form->{'Values'}->{'cds_surname'} = [$Servlet->params('cds_surname')];

        #    $Servlet->form->executeFormError();

#this is to handle the case when the cds check button hasn't been clicked - ie. user clicked register button
#we may still have cds fields filled in but may have been tampered by user so if they are do the CDS check before registering.
#          GetLog->error('Register button may have been clicked..');
#          $Servlet->form->{'Values'}->{'cifnumber'} = [$Servlet->params('cifnumber')];
#          $Servlet->form->{'Values'}->{'dob'} = [$Servlet->params('dob')];
#         $Servlet->form->{'Values'}->{'cds_surname'} = [$Servlet->params('cds_surname')];
#
#          if (defined($Servlet->params('cifnumber')) && $Servlet->params('cifnumber') =~ /^\d{4,}$/ && defined($Servlet->params('dob')) && defined($Servlet->params('cds_surname'))){
#              GetLog->error('CDS fields are defined so checking with CDS');
#             #only do CDS check if all three CDS fields are there
#         #    my $hMemberInfo = &BIG_B2C::CDS::API::CDS::GetCDSInfo($Servlet->params('cifnumber'),$Servlet->params('dob'),$Servlet->params('cds_surname'),'D');
#  $hMemberInfo->{'errorcode'} = 'error';
#             if ($hMemberInfo->{'errorcode'} ne 'Success'){
#                GetLog->error('CDS Check ERROR');
#                 #ok.. something wrong so throw error
#                 $Servlet->vars('CDSReason', $hMemberInfo->{'errorcode'});
#                 $Servlet->form->addFormError( {
#                    Reason => 'CDSError',
#                    Name => 'cifnumber',
#                 });
#             }else{
#                #success.. this should get passed through to post login hook
#                GetLog->error('CDS Check successfull..moving on');
#                $Servlet->form->{'Values'}->{'insert_cds_info'} = [1];
#                $Servlet->form->{'Values'}->{'cohortid'} = [$hMemberInfo->{'cohortid'}];

            #            }
            #          }

        }
    }

    #end sub

}

sub trim {
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    $string =~ s/\s+//g;
    return $string;
}

1;
